<template>
  <div class="settings-view">
    <div class="header">
      <h2>系统设置</h2>
    </div>

    <el-form
      ref="formRef"
      :model="settings"
      label-width="120px"
      class="settings-form"
    >
      <!-- 基本设置 -->
      <el-card class="mb-4">
        <template #header>
          <div class="card-header">
            <span>基本设置</span>
          </div>
        </template>

        <el-form-item label="系统名称">
          <el-input v-model="settings.systemName" />
        </el-form-item>

        <el-form-item label="系统描述">
          <el-input
            v-model="settings.systemDescription"
            type="textarea"
            rows="3"
          />
        </el-form-item>

        <el-form-item label="系统Logo">
          <upload-field v-model="settings.systemLogo" accept="image/*" />
        </el-form-item>
      </el-card>

      <!-- AI服务器设置 -->
      <el-card class="mb-4">
        <template #header>
          <div class="card-header">
            <span>AI服务器设置</span>
            <el-button type="primary" @click="addServer">
              添加服务器
            </el-button>
          </div>
        </template>

        <div
          v-for="(server, index) in settings.servers"
          :key="server.id"
          class="server-item"
        >
          <div class="server-header">
            <h4>服务器 {{ index + 1 }}</h4>
            <el-button
              type="danger"
              size="small"
              @click="removeServer(index)"
            >
              删除
            </el-button>
          </div>

          <el-form-item :label="'服务器名称'">
            <el-input v-model="server.name" />
          </el-form-item>

          <el-form-item :label="'服务器地址'">
            <el-input v-model="server.url" />
          </el-form-item>

          <el-form-item :label="'服务器类型'">
            <el-select v-model="server.type">
              <el-option label="Stable Diffusion" value="sd" />
              <el-option label="ComfyUI" value="comfyui" />
              <el-option label="其他" value="other" />
            </el-select>
          </el-form-item>

          <el-form-item :label="'服务器状态'">
            <el-tag :type="getServerStatusType(server.status)">
              {{ getServerStatusText(server.status) }}
            </el-tag>
            <el-button
              size="small"
              class="ml-2"
              @click="testServer(server)"
            >
              测试连接
            </el-button>
          </el-form-item>
        </div>
      </el-card>

      <!-- 存储设置 -->
      <el-card class="mb-4">
        <template #header>
          <div class="card-header">
            <span>存储设置</span>
          </div>
        </template>

        <el-form-item label="存储类型">
          <el-radio-group v-model="settings.storage.type">
            <el-radio label="local">本地存储</el-radio>
            <el-radio label="oss">阿里云OSS</el-radio>
            <el-radio label="cos">腾讯云COS</el-radio>
          </el-radio-group>
        </el-form-item>

        <template v-if="settings.storage.type === 'oss'">
          <el-form-item label="AccessKey">
            <el-input v-model="settings.storage.accessKey" />
          </el-form-item>
          <el-form-item label="SecretKey">
            <el-input v-model="settings.storage.secretKey" type="password" />
          </el-form-item>
          <el-form-item label="Bucket">
            <el-input v-model="settings.storage.bucket" />
          </el-form-item>
          <el-form-item label="Region">
            <el-input v-model="settings.storage.region" />
          </el-form-item>
        </template>
      </el-card>

      <!-- 保存按钮 -->
      <div class="form-actions">
        <el-button type="primary" :loading="saving" @click="save">
          保存设置
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { v4 as uuidv4 } from 'uuid'
import UploadField from '@/components/UploadField.vue'

interface ServerConfig {
  id: string
  name: string
  url: string
  type: string
  status: 'online' | 'offline' | 'error'
}

interface StorageConfig {
  type: 'local' | 'oss' | 'cos'
  accessKey?: string
  secretKey?: string
  bucket?: string
  region?: string
}

interface SystemSettings {
  systemName: string
  systemDescription: string
  systemLogo: string
  servers: ServerConfig[]
  storage: StorageConfig
}

const formRef = ref()
const saving = ref(false)

// 系统设置
const settings = ref<SystemSettings>({
  systemName: '',
  systemDescription: '',
  systemLogo: '',
  servers: [],
  storage: {
    type: 'local'
  }
})

// 获取设置
const getSettings = async () => {
  try {
    const response = await fetch('/api/settings')
    const data = await response.json()
    settings.value = data
  } catch (error) {
    console.error('Failed to get settings:', error)
    ElMessage.error('获取设置失败')
  }
}

// 添加服务器
const addServer = () => {
  settings.value.servers.push({
    id: uuidv4(),
    name: '',
    url: '',
    type: 'sd',
    status: 'offline'
  })
}

// 删除服务器
const removeServer = (index: number) => {
  settings.value.servers.splice(index, 1)
}

// 测试服务器连接
const testServer = async (server: ServerConfig) => {
  try {
    const response = await fetch(`${server.url}/ping`)
    if (response.ok) {
      server.status = 'online'
      ElMessage.success('连接成功')
    } else {
      server.status = 'error'
      ElMessage.error('连接失败')
    }
  } catch (error) {
    server.status = 'error'
    ElMessage.error('连接失败')
  }
}

// 获取服务器状态类型
const getServerStatusType = (status: string) => {
  switch (status) {
    case 'online':
      return 'success'
    case 'offline':
      return 'info'
    case 'error':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取服务器状态文本
const getServerStatusText = (status: string) => {
  switch (status) {
    case 'online':
      return '在线'
    case 'offline':
      return '离线'
    case 'error':
      return '错误'
    default:
      return status
  }
}

// 保存设置
const save = async () => {
  try {
    saving.value = true
    await fetch('/api/settings', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(settings.value)
    })
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('Failed to save settings:', error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 初始化
onMounted(() => {
  getSettings()
})
</script>

<style scoped lang="scss">
.settings-view {
  padding: 24px;

  .header {
    margin-bottom: 24px;

    h2 {
      margin: 0;
    }
  }

  .settings-form {
    max-width: 800px;

    .mb-4 {
      margin-bottom: 24px;
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .server-item {
      margin-bottom: 24px;
      padding: 16px;
      border: 1px solid #eee;
      border-radius: 4px;

      &:last-child {
        margin-bottom: 0;
      }

      .server-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;

        h4 {
          margin: 0;
        }
      }
    }

    .form-actions {
      margin-top: 24px;
      text-align: right;
    }
  }
}
</style> 